package com.heatup.apt.management.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.heatup.apt.common.dao.DataCenterMapper;
import com.heatup.apt.common.util.DateUtils;
import com.heatup.apt.common.util.JsonTools;
import com.heatup.apt.common.util.RequestTools;
import com.heatup.apt.common.util.ResponseTools;
import com.heatup.apt.management.service.datacenter.DataAnalysisService;
import com.heatup.apt.model.api.ApiResultModel;

/**
 * 数据分析控制器
 * 
 * @author jixiangyun 2017年4月10日 下午12:18:53
 */
@Controller
@RequestMapping("/system/data")
public class DataAnalysisController extends BaseController {

	private Logger logger = LoggerFactory.getLogger(DataAnalysisController.class);

	@Autowired
	private DataAnalysisService dataAnalysisService;
	@Autowired 
	private DataCenterMapper  dataCenterMapper;

	/**
	 * 大盘数据分析跳转页面
	 * 
	 * @return
	 */
	@RequestMapping("/data_analysis")
	public ModelAndView dataAnalysis() {
		ModelAndView model = new ModelAndView();
		model.setViewName("data/data_index");
		return model;
	}

	/**
	 * 大盘数据中心第一层数据异步加载
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/data_level_one")
	public String analysisLevelOne(HttpServletRequest request, HttpServletResponse response) {
		ApiResultModel<Object> apiResultModel = new ApiResultModel<>();
		String callback = RequestTools.RequestString(request, "callback", null);
		String type = RequestTools.RequestString(request, "type", "1");
		String dateTime = RequestTools.RequestString(request, "dateTime", null);
		Integer storeId = RequestTools.RequestInt(request, "storeId", 0);
		Map<String, Object> parameMap = new HashMap<>();
		try {
			parameMap.put("type", type);
			parameMap.put("dateTime", dateTime);
			parameMap.put("storeId", storeId);
			parameMap = dataAnalysisService.queryDataAnalysisLevelOne(parameMap);
			apiResultModel.setData(parameMap);
		} catch (Exception e) {
			apiResultModel.setErrorCode(ApiResultModel.RET_ERROR);
			apiResultModel.setRet(ApiResultModel.RET_ERROR);
			apiResultModel.setMsg("系统异常");
			logger.info("============================== ajax analysis_level_one error: " + e.getMessage());
		}
		return ResponseTools.CallBackResultJsonP(JsonTools.jsonSer(apiResultModel), callback);
	}

	/**
	 * 大盘数据中心第二层数据异步加载
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/data_level_tow")
	public String analysisLevelTow(HttpServletRequest request, HttpServletResponse response) {
		ApiResultModel<Object> apiResultModel = new ApiResultModel<>();
		String callback = RequestTools.RequestString(request, "callback", null);
		String type = RequestTools.RequestString(request, "type", "1");
		String dateTime = RequestTools.RequestString(request, "dateTime", null);
		Integer storeId = RequestTools.RequestInt(request, "storeId", 0);
		Map<String, Object> parameMap = new HashMap<>();
		try {
			parameMap.put("type", type);
			parameMap.put("dateTime", dateTime);
			parameMap.put("storeId", storeId);
			parameMap = dataAnalysisService.queryDataAnalysisLevelTow(parameMap);
			apiResultModel.setData(parameMap);
		} catch (Exception e) {
			apiResultModel.setErrorCode(ApiResultModel.RET_ERROR);
			apiResultModel.setRet(ApiResultModel.RET_ERROR);
			apiResultModel.setMsg("系统异常");
			logger.info("============================== ajax analysis_level_one error: " + e.getMessage());
		}
		return ResponseTools.CallBackResultJsonP(JsonTools.jsonSer(apiResultModel), callback);
	}

	/**
	 * 大盘数据中心第二层数据异步加载
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/data_level_three")
	public String analysisLevelThree(HttpServletRequest request, HttpServletResponse response) {
		ApiResultModel<Object> apiResultModel = new ApiResultModel<>();
		String callback = RequestTools.RequestString(request, "callback", null);
		String type = RequestTools.RequestString(request, "type", "1");
		String dateTime = RequestTools.RequestString(request, "dateTime", null);
		Integer storeId = RequestTools.RequestInt(request, "storeId", 0);
		Map<String, Object> parameMap = new HashMap<>();
		try {
			parameMap.put("type", type);
			parameMap.put("dateTime", dateTime);
			parameMap.put("storeId", storeId);
			parameMap = dataAnalysisService.queryDataAnalysisLevelThree(parameMap);
			apiResultModel.setData(parameMap);
		} catch (Exception e) {
			apiResultModel.setErrorCode(ApiResultModel.RET_ERROR);
			apiResultModel.setRet(ApiResultModel.RET_ERROR);
			apiResultModel.setMsg("系统异常");
			logger.info("============================== ajax analysis_level_one error: " + e.getMessage());
		}
		return ResponseTools.CallBackResultJsonP(JsonTools.jsonSer(apiResultModel), callback);
	}

	/**
	 * 大盘数据中心第二层数据异步加载
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/data_level_four")
	public String analysisLevelFour(HttpServletRequest request, HttpServletResponse response) {
		ApiResultModel<Object> apiResultModel = new ApiResultModel<>();
		String callback = RequestTools.RequestString(request, "callback", null);
		String type = RequestTools.RequestString(request, "type", "1");
		String dateTime = RequestTools.RequestString(request, "dateTime", null);
		Integer storeId = RequestTools.RequestInt(request, "storeId", 0);
		Map<String, Object> parameMap = new HashMap<>();
		try {
			parameMap.put("type", type);
			parameMap.put("dateTime", dateTime);
			parameMap.put("storeId", storeId);
			parameMap = dataAnalysisService.queryDataAnalysisLevelFour(parameMap);
			apiResultModel.setData(parameMap);
		} catch (Exception e) {
			apiResultModel.setErrorCode(ApiResultModel.RET_ERROR);
			apiResultModel.setRet(ApiResultModel.RET_ERROR);
			apiResultModel.setMsg("系统异常");
			logger.info("============================== ajax analysis_level_one error: " + e.getMessage());
		}
		return ResponseTools.CallBackResultJsonP(JsonTools.jsonSer(apiResultModel), callback);
	}

	/**
	 * 汇总类数据 汇总类数据（2016.12.01至当前的数据汇总） 这个日期是否写死？
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/summary_data_to_date")
	public String summaryDataToDate(HttpServletRequest request, HttpServletResponse response) {
		ApiResultModel<Object> apiResultModel = new ApiResultModel<>();
		String callback = RequestTools.RequestString(request, "callback", null);
		Integer storeId = RequestTools.RequestInt(request, "storeId", 0);
		Map<String, Object> parameMap = new HashMap<>();
		try {
			parameMap.put("storeId", storeId);
			parameMap = dataAnalysisService.querySummaryDataToNow(parameMap);
			apiResultModel.setData(parameMap);
		} catch (Exception e) {
			apiResultModel.setErrorCode(ApiResultModel.RET_ERROR);
			apiResultModel.setRet(ApiResultModel.RET_ERROR);
			apiResultModel.setMsg("系统异常");
			logger.info("============================== ajax analysis_level_one error: " + e.getMessage());
		}

		return ResponseTools.CallBackResultJsonP(JsonTools.jsonSer(apiResultModel), callback);
	}

	/**
	 * 教练复购率排行
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/ranking_to_coach")
	public String rankingToCoach(HttpServletRequest request, HttpServletResponse response) {
		ApiResultModel<Object> apiResultModel = new ApiResultModel<>();
		String callback = RequestTools.RequestString(request, "callback", null);
		String dateTime = RequestTools.RequestString(request, "dateTime", null);
		Map<String,Object> parameMap = new HashMap<>();
		parameMap.put("dateTime", dateTime);
		try {
			parameMap = dataAnalysisService.repurchaseRateRankingToCoach(parameMap);
			apiResultModel.setData(parameMap);
			apiResultModel.setErrorCode(apiResultModel.RET_SUCCESS);
			apiResultModel.setRet(apiResultModel.RET_SUCCESS);
			apiResultModel.setMsg("教练复购率排行");
		} catch (Exception e) {
			apiResultModel.setErrorCode(apiResultModel.RET_ERROR);
			apiResultModel.setRet(apiResultModel.RET_ERROR);
			apiResultModel.setMsg("系统异常");
			logger.info("============================== ajax analysis_level_one error: "+e.getMessage());
		}
		return ResponseTools.CallBackResultJsonP(JsonTools.jsonSer(apiResultModel), callback);
	}

	/**
	 * 课程重复购买率排名
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/ranking_to_course")
	public String rankingToCourse(HttpServletRequest request, HttpServletResponse response) {
		ApiResultModel<Object> apiResultModel = new ApiResultModel<>();
		String callback = RequestTools.RequestString(request, "callback", null);
		String dateTime = RequestTools.RequestString(request, "dateTime", null);
		Map<String,Object> parameMap = new HashMap<>();
		parameMap.put("dateTime", dateTime);
		try {
			parameMap = dataAnalysisService.repurchaseRateRankingToCourse(parameMap);
			apiResultModel.setData(parameMap);
			apiResultModel.setErrorCode(apiResultModel.RET_SUCCESS);
			apiResultModel.setRet(apiResultModel.RET_SUCCESS);
			apiResultModel.setMsg("课程重复购买率排名");
		} catch (Exception e) {
			apiResultModel.setErrorCode(apiResultModel.RET_ERROR);
			apiResultModel.setRet(apiResultModel.RET_ERROR);
			apiResultModel.setMsg("系统异常");
			logger.info("============================== ajax analysis_level_one error: "+e.getMessage());
		}

		return ResponseTools.CallBackResultJsonP(JsonTools.jsonSer(apiResultModel), callback);
	}

	/**
	 * 团课满课率排名
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/ranking_to_team")
	public String rankingToTeam(HttpServletRequest request, HttpServletResponse response) {
		ApiResultModel<Object> apiResultModel = new ApiResultModel<>();
		String callback = RequestTools.RequestString(request, "callback", null);
		String dateTime = RequestTools.RequestString(request, "dateTime", null);
		Map<String,Object> parameMap = new HashMap<>();
		parameMap.put("dateTime", dateTime);
		try {
			parameMap = dataAnalysisService.teamFullClassRateRanking(parameMap);
			apiResultModel.setData(parameMap);
			apiResultModel.setErrorCode(apiResultModel.RET_SUCCESS);
			apiResultModel.setRet(apiResultModel.RET_SUCCESS);
			apiResultModel.setMsg("团课满课率排名");
		} catch (Exception e) {
			apiResultModel.setErrorCode(apiResultModel.RET_ERROR);
			apiResultModel.setRet(apiResultModel.RET_ERROR);
			apiResultModel.setMsg("系统异常");
			logger.info("============================== ajax analysis_level_one error: "+e.getMessage());
		}
		return ResponseTools.CallBackResultJsonP(JsonTools.jsonSer(apiResultModel), callback);
	}
	
	@ResponseBody
	@RequestMapping("data_analysis_detail")
	public String dataAnalysisDetail(HttpServletRequest request,HttpServletResponse response){
		ApiResultModel<Object> apiResultModel = new ApiResultModel<>();
		String callback = RequestTools.RequestString(request, "callback", null);
		String dateTime = RequestTools.RequestString(request, "dateTime", null);
		String type = RequestTools.RequestString(request, "type", "1");
		String query_type = RequestTools.RequestString(request, "query_type", null);
		String mode_type = RequestTools.RequestString(request, "mode_type", null);
		Integer storeId = RequestTools.RequestInt(request, "storeId", 0);
		Map<String,Object> parameMap = new HashMap<>();
		parameMap.put("dateTime", dateTime);
		parameMap.put("type", type);
		parameMap.put("query_type", query_type);
		parameMap.put("mode_type", mode_type);
		parameMap.put("storeId", storeId);
		try {
			parameMap = dataAnalysisService.dataAnalysisDetail(parameMap);
			apiResultModel.setData(parameMap);
			apiResultModel.setErrorCode(apiResultModel.RET_SUCCESS);
			apiResultModel.setRet(apiResultModel.RET_SUCCESS);
			apiResultModel.setMsg("查询大盘数据明细");
		} catch (Exception e) {
			apiResultModel.setErrorCode(apiResultModel.RET_ERROR);
			apiResultModel.setRet(apiResultModel.RET_ERROR);
			apiResultModel.setMsg("系统异常");
			logger.info("============================== ajax analysis_level_one error: "+e.getMessage());
		}
		return ResponseTools.CallBackResultJsonP(JsonTools.jsonSer(apiResultModel), callback);
	}

	/**
	 * 门店经营分析数据
	 * @param request
	 * @param response
	 */
	@ResponseBody
	@RequestMapping(value = "/queryStoreBusinessAnalysisData")
	public void queryStoreBusinessAnalysisData(HttpServletRequest request, HttpServletResponse response) {
		Integer storeId = RequestTools.RequestInt(request, "storeId", 0);
		String yearMonth = RequestTools.RequestString(request, "yearMonth", null);
		try {
			if (yearMonth == null || "".equals(yearMonth)) {
				Calendar cal = Calendar.getInstance();
				cal.add(Calendar.MONTH, -1);
				Date lastMonth = cal.getTime();
				yearMonth = new SimpleDateFormat("yyyy-MM").format(lastMonth);
			}
			Map<String, Object> paramMap = new HashMap<String, Object>();
			paramMap.put("storeId", storeId);
			paramMap.put("yearMonth", yearMonth);
			Map<String, Object> respMap = dataAnalysisService.storeFinancialAnalysisData(paramMap);
			respMap.put("yearMonth", yearMonth);
			this.responseSendMsg(response, JSONObject.toJSONString(respMap));
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("查询门店经营分析数据异常：",e);
		}
	}
	/**
	 * 收支曲线图
	 * @param request
	 * @param response
	 */
	@ResponseBody
	@RequestMapping(value = "/queryBalanceMapByYearMonthRange")
	public void queryBalanceMapByYearMonthRange(HttpServletRequest request, HttpServletResponse response) {
		Integer storeId = RequestTools.RequestInt(request, "storeId", 0);
		String month_range = RequestTools.RequestString(request, "month_range", null);
		Map<String,Object> paramMap = new HashMap<String,Object>();
		paramMap.put("storeId", storeId);
		Map<String,Object> respMap = new HashMap<String,Object>();
		String minYearMonth=null;
		String maxYearMonth=null;
		List<String> yearMonthList=new ArrayList<String>();
		try {
			String range[] = null;
			if(month_range !=null){
				range = month_range.split("~");	
				minYearMonth= range[0];
				maxYearMonth= range[1];
				yearMonthList = DateUtils.getMonthBetween(minYearMonth, maxYearMonth);
				
			}
			paramMap.put("yearMonthList", yearMonthList);
			respMap =	dataAnalysisService.queryBalanceMapByYearMonthRange(paramMap);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("收支曲线图异常：",e);
		}
		this.responseSendMsg(response, JSONObject.toJSONString(respMap));
	}
	
	/**
	 * 门店月份相关收支金额信息更新
	 * @param request
	 * @param response
	 */
	@ResponseBody
	@RequestMapping(value = "/saveOrUpdateStoreBalanceDetail")
	public void saveOrUpdateStoreBalanceDetail(HttpServletRequest request, HttpServletResponse response){
		Integer storeId = RequestTools.RequestInt(request, "storeId", 0);
		String yearMonth = RequestTools.RequestString(request, "yearMonth", null);
		String type = RequestTools.RequestString(request, "type", null);//
		String updateAmt = RequestTools.RequestString(request, "updateAmt", "0");
		Map<String,Object> respMap = new HashMap<String,Object>();
		Map<String,Object> paramMap = new HashMap<String,Object>();
		paramMap.put("storeId", storeId);
		paramMap.put("yearMonth", yearMonth);
		paramMap.put("type", type);
		paramMap.put("updateAmt", updateAmt);
		try{
			dataAnalysisService.saveOrUpdateStoreBalanceDetail(paramMap);
			respMap.put("msg", "success");
		}catch(Exception e){
			e.printStackTrace();
			respMap.put("msg", "error");
			logger.error("保存门店月份收支情况异常",e);
		}
		this.responseSendMsg(response, JSONObject.toJSONString(respMap));
	}
	
	/**
	 * 统计门店的包月卡数据
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/data_level_month_card")
	public String analysisMonthCard(HttpServletRequest request, HttpServletResponse response) {
		ApiResultModel<Object> apiResultModel = new ApiResultModel<>();
		String callback = RequestTools.RequestString(request, "callback", null);
		String type = RequestTools.RequestString(request, "type", "1");
		String dateTime = RequestTools.RequestString(request, "dateTime", null);
		Integer storeId = RequestTools.RequestInt(request, "storeId", 0);
		Map<String, Object> parameMap = new HashMap<>();
		try {
			if(storeId > 0){
				Integer bool = dataCenterMapper.queryStoreIsHaveCard(storeId);
				if(bool < 1){
					apiResultModel.setErrorCode(ApiResultModel.RET_ERROR);
					apiResultModel.setRet(ApiResultModel.RET_ERROR);
					apiResultModel.setMsg("该门店没有包月卡");
					return ResponseTools.CallBackResultJsonP(JsonTools.jsonSer(apiResultModel), callback);
				}
			}
			parameMap.put("type", type);
			parameMap.put("dateTime", dateTime);
			parameMap.put("storeId", storeId);
			parameMap = dataAnalysisService.queryMonthCard(parameMap);
			apiResultModel.setData(parameMap);
		} catch (Exception e) {
			apiResultModel.setErrorCode(ApiResultModel.RET_ERROR);
			apiResultModel.setRet(ApiResultModel.RET_ERROR);
			apiResultModel.setMsg("系统异常");
			logger.info("============================== ajax data_level_month_card error: " + e.getMessage());
		}
		return ResponseTools.CallBackResultJsonP(JsonTools.jsonSer(apiResultModel), callback);
	}
}
